package deepbrain.iit;

import java.util.ArrayList;
import java.util.List;

public class Partition<T> implements Cloneable {

	public ArrayList<ArrayList<T>> partition;

	public Partition() {
		partition = new ArrayList<ArrayList<T>>();
	}

	public Partition(int numOfParts) {
		partition = new ArrayList<ArrayList<T>>();
		for (int i = 0; i < numOfParts; i++)
			partition.add(new ArrayList<T>());
	}

	public Partition(ArrayList<ArrayList<T>> partition) {
		this.partition = partition;
	}

	public int numOfParts() {
		return partition.size();
	}

	public ArrayList<T> part(int n) {
		return partition.get(n);
	}

	public void addPart() {
		partition.add(new ArrayList<T>());
	}

	public void addPart(ArrayList<T> part) {
		partition.add(part);
	}

	public void setPart(int i, ArrayList<T> part) {
		partition.set(i, part);
	}

	public ArrayList<ArrayList<T>> getPartition() {
		return partition;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder(100);
		int i = 0, j = 0;
		builder.append("[");
		for (i = 0; i < partition.size(); i++) {
			List<T> part = partition.get(i);
			builder.append("[");
			for (j = 0; j < part.size() - 1; j++) {
				builder.append(part.get(j));
				builder.append(", ");
			}
			builder.append(part.get(j));
			builder.append("]");
			if (i < partition.size() - 1)
				builder.append(", ");
		}
		builder.append("]");
		return builder.toString();
	}

	public static Partition<Integer> parsePartition(String line) {
		String[] pieces = line.trim().split("], ");
		Partition<Integer> partition = new Partition<Integer>();
		ArrayList<Integer> part;
		for (int i = 0; i < pieces.length; i++) {
			part = new ArrayList<Integer>();
			String partStr = pieces[i];
			while (partStr.startsWith("["))
				partStr = partStr.substring(1);
			while (partStr.endsWith("]"))
				partStr = partStr.substring(0, partStr.length() - 1);
			while (partStr.endsWith(", "))
				partStr = partStr.substring(0, partStr.length() - 2);
			String[] elements = partStr.split(", ");
			for (String element : elements)
				part.add(Integer.parseInt(element.trim()));
			partition.addPart(part);
		}
		return partition;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Partition<T> clone() {
		return new Partition<T>((ArrayList<ArrayList<T>>) partition.clone());
	}

}
